import os
import requests
import json
import hashlib
import urllib
import collections
import datetime
import math

def md5(src):
    m2=hashlib.md5()
    m2.update(src.encode("utf-8"))
    return m2.hexdigest()

def fromtimestramp(d):
    return datetime.datetime.fromtimestamp(d)

    

def urlparam(d):
    kd = collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))
    return urllib.parse.urlencode(kd)

def unurlparam(d):
    return urllib.parse.unquote_plus(urlparam(d))

def auth(d):
    j=json.dumps(d,sort_keys=True).strip()
    metadata = json.loads(j, object_pairs_hook=collections.OrderedDict);        # 一定要复制一个新的对象，不然会修改原来的对象
    if metadata.get("order_list")!=None:
        metadata["order_list"]=json.dumps(metadata["order_list"]).strip().replace(' ',"")
    a=unurlparam(metadata)+"kosun.net"
    return a

name = "woddle"
pwd = "abc1234"
#md5("act=10022&is_special_agent=0&password=abc1234&user_name=woddlekosun.net")
url = "https://cp899.kosunmobile.com/Mobile"
param = {"act": 10022, "is_special_agent": 0,"password": "abc1234", "user_name": "woddle"}
kd = collections.OrderedDict(sorted(param.items(), key=lambda t: t[0]))
authorization=md5(urlparam(param)+"kosun.net")              #md5(urllib.parse.urlencode(kd)+ "kosun.net")
headers={"Content-Type":"application/json; charset=utf-8",
         "authorization":authorization,
         "accept":"application/json","user-agent":"ios"}

r = requests.post(url, data=json.dumps(param), verify=False,headers=headers)
print(r.text)
token=r.json()["token"]


def exit():
    headers["token"]=token
    headers["authorization"]=md5(urlparam({"act":"10037"}) + "kosun.net")   #"4680037428e660a688c35f804990cc9c"
    a = requests.post(url,data=json.dumps({"act":"10037"}),verify=False,headers=headers,
                      cookies=r.cookies)
    print(a.text)


def get_now_issue():
    param={"act":10003,"lottery_id":"1"}

    headers["authorization"]=md5(auth(param))
    a = requests.post(url,data=json.dumps(param),verify=False,headers=headers,
                      cookies=r.cookies)
    j = a.json()
    return j["issue_no"]

def get_last_20():
    param={"act": 10005,"lottery_id": "1"}
    headers["authorization"]=md5(auth(param))
    a = requests.post(url,data=json.dumps(param),verify=False,headers=headers,
                      cookies=r.cookies)
    print(a.text)
    return 1

# 将1.0变成1 2.1变成2.1
def getval(d):
    return 

def get_buy_type(play="后三组三",mode=3):
    table={"后三组三":27,"后三组六":28,"前三组三":39,"前三组六":40,"中三组三":33,"中三组六":34}
    totalmoney={0:{"money":240,"nums":120},1:{"money":180,"nums":90}}
    issue=get_now_issue()
    data={
	"act": 10006,
	"lottery_id": "1",              # 彩票类型
	"order_list": [{
		"play_id": "27",        # 玩法类型 27：后三组三  28：后三组六 39：前三组三 40：前三组六  33：中三组三 34：中三组六
		"content": "0,1,2,3,4,5,6,7,8,9",
		"mode": 1,              # 百分比类型 1：1  2:0.1  3：0.01
		"point": "0.0",
		"nums": 90,             # 所选的组合个数
		"price": 2,             # 每组的钱数 只能是整数
		"money": 180            # 投入钱数
	}],
	"plan_list": [],
	"win_stop": 0,
	"issue_no": "20171109090"
    }
    t = table[play] % 2
    money=totalmoney[t]["money"] * math.pow(10,(int(mode)-1) * -1)
    money=[float(money),int(money)][int(money)==money]
    data["order_list"][0]["play_id"]=str(table[play])
    data["order_list"][0]["mode"]=int(mode)
    data["order_list"][0]["money"]=money
    data["order_list"][0]["nums"]=totalmoney[t]["nums"]
    data["issue_no"]=issue
    return data

def buy(play="后三组三",mode=3):
    headers["token"]=token
    
    data=get_buy_type(play,mode)
    c="act=203&issue_no=20171109041&lottery_id=1&order_list=[{\"content\":\"0,1,2,3,4,5,6,7,8,9\",\"method_name\":\"housan_housanzuxuan_zusan\",\"mode\":1,\"money\":180,\"nums\":90,\"play_id\":\"27\",\"point\":\"0.0\",\"price\":2}]&plan_list=[]&win_stop=0kosun.net"
    headers["authorization"]=md5(auth(data)) #"d3e10f0d5eadcaf8ed483fbd86ae7aef"
    a = requests.post(url,data=json.dumps(data),verify=False,headers=headers,
                      cookies=r.cookies)
    print(a.text)
